package com.example.demo.mapper;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWT {
    private static final long JWT_EXPIRATION = 60 * 60 * 1000;
    private static final String secretStr = "Le++o8NQWVXWo3+SJtAtnjBW9iA0OvPL0c0mMrol2fU=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));
    //private static final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    /*
    生成jwt
     */
    @Test
    public void getToken(){
       Map<String,Object> map=new HashMap<>();
       map.put("id",1);
       map.put("username","zhangsan");
       String token= Jwts.builder().setClaims(map)
               .setExpiration(new Date(System.currentTimeMillis()+JWT_EXPIRATION))
               .signWith(key)
               .compact();
        System.out.println(token);
    }

    @Test
    public void parseToken(){
        String token ="eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ6aGFuZ3NhbiIsImV4cCI6MTc0MTc1Mjc4N30.cyDRwQGiD_vOxilEkfBT9NuL-asPPqwN0fEP7NPSujE";
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = build.parseClaimsJws(token).getBody();
        System.out.println(claims);
    }
}
